const getTime = (date, type) => {
  var str = ""
  if (!date) {
    str = parseInt(new Date() / 1000)
  } else {
    date = new Date(date*1000)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    switch (type) {
      case '.':
        str = year + '.' + month + '.' + day
        break;
      case '/':
        str = year + '/' + month + '/' + day
        break;
      case '-':
        str = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
        break;
      case 'arr':
        str = [year,month,day,hour,minute,second]
        break;
      case 'cn':
        str = year + '年' + month + '月' + day + '日'
        break;

      default:
        str = year + '-' + month + '-' + day
        break;
    }
  }

  return str
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const escape2Html = (str) => {
  var arrEntities = {
    'lt': '<',
    'gt': '>',
    'nbsp': ' ',
    'amp': '&',
    'quot': '"'
  };
  return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
    return arrEntities[t];
  }).replace('<section', '<div').replace('<img', '<img style="max-width:100%;height:auto" ');
}

const richContentFormat = (str) => {
  return str.replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
    .replace(/<p>/ig, '<p style="font-size: 15px; line-height: 25px;margin-bottom:10px;">')
    .replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/ig, '<img$1')
    .replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/ig, '<img$1')
    .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
    .replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/ig, '<img$1')
    .replace(/<img([\s\w"-=\/\.:;]+)/ig, '<img style="width: 100%;" $1');
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  getTime: getTime,
  formatTime: formatTime,
  escape2Html: escape2Html,
  richContentFormat: richContentFormat
}